<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">

var openedId = 'extension_opned' ;
var formTab = null ;

function onRequest( request, sender, callback ) {
  if( request.action == 'available' ) {
    var available = formTab ? true : false ;
    callback( available ) ;
  }
}

function clickIcon( tab ) {
  if( formTab ) {
    chrome.tabs.remove( formTab.id ) ;
    formTab = null ;
    localStorage.setItem( openedId, 'false' ) ;
  } else {
    openExtension( ) ;
    localStorage.setItem( openedId, 'true' ) ;
  }
}

function removeTab( id, info ) {
  if( formTab && id == formTab.id )
    formTab = null ;
}

function openExtension( ) {
  chrome.tabs.create( { url: 'chrome-extension://' + String( location.host ) + '/form.html' },
                       function( tab ) { formTab = tab ; } ) ;
}

chrome.tabs.onRemoved.addListener( removeTab ) ;
chrome.extension.onRequest.addListener( onRequest ) ;
chrome.browserAction.onClicked.addListener( clickIcon ) ;

if( ! localStorage.getItem( openedId ) || localStorage.getItem( openedId ) == 'true' )
  openExtension( ) ;

if( ! localStorage.getItem( openedId ) )
  localStorage.setItem( openedId, 'true' ) ;
  

</script>
</body>
</html>
